//
//  NetWorkTools.swift
//  SinaWb
//
//  Created by Jiang on 16/5/14.
//  Copyright © 2016年 Jiang. All rights reserved.
//
//

import UIKit
import AFNetworking
import SVProgressHUD

enum  HTTPRequstMethod : String{
    case GET = "GET"
    case POST = "POST"
}

class NetWorkTools: AFHTTPSessionManager {
    //MARK: - NetWorkTools的单例
    static  let sharNetWorkTools :NetWorkTools = {
        
        let instance = NetWorkTools(baseURL: nil)
        
        instance.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        instance.requestSerializer.timeoutInterval = 10
        
        return instance
    }()
    
    //MARK: - 封装AFN dataTaskWithHTTPMethod
    func request(   requstMethod:  HTTPRequstMethod,
                    URLString :    String,
                    parameter :    AnyObject ,
                    Right:  (result:AnyObject?)->(),
                    Wrong:    (Error:NSError?)->()  ) {
        
        dataTaskWithHTTPMethod(requstMethod.rawValue, URLString: URLString, parameters: parameter, uploadProgress: nil, downloadProgress: nil, success:
            { (_, object) in
                
                Right(result: object)
            }) { (_, error) in
                
                Wrong(Error: error)
        }.resume()
    }
    
    //MARK: - LoginViewController的webView代理的处理
    //MARK: 1. 获取code
    func requstJudge(requset : NSURLRequest) -> (Bool,String?){
        guard let urlstring = requset.URL?.absoluteString else{
            return (false,nil)
        }
        if !urlstring.hasPrefix("https://api.weibo.com/oauth2"){

            return  (false,nil)
        }
        if !urlstring.hasPrefix(uri){
            return (true,nil)
        }
        
        guard let query = requset.URL?.query else{
            
            return (true,nil)
        }
        
        let substring = "code="
        let code = query.substringFromIndex(substring.endIndex)
        
        return (false,code)
    }
    
    //MARK: 2. 使用Code获取Accec_taken,再获取用户JSON数据
    /**
     
     - parameter code:          Code
     - parameter AcessTakenURL: 获取Acess_Taken的地址
     - parameter paramete:      POST请求的字典
     - parameter UserURLString: 获取用户信息的字典
     - parameter Complete:      完成回调函数
     - parameter WithError:     错误回调函数
     */
    func GetAcessTaken(AcessTakenURL:String,paramete:AnyObject,UserURLString:String,Complete:(usermode:AnyObject) -> () , WithError:(errors : NSError?)->()){
        
        SVProgressHUD.show()
        
        request(.POST, URLString: AcessTakenURL, parameter: paramete, Right: { (result) in

            if let tokendic = result as? [String:AnyObject]{
                        //闭包嵌套
                        self.GetUserModel(tokendic,UserURLString:UserURLString, Complete: Complete, WithError: WithError)
                }
            
            },Wrong: { (Error) in
                
                    WithError(errors: Error)
            }
        )
    }
    
    //MARK: 3.获取的JSON数据转模型

   private func GetUserModel(tokendic :[String:AnyObject],
                      UserURLString:String,
                      Complete:(usermode:AnyObject) -> () ,
                      WithError:(errors : NSError?)->()){
    
        let user : UserModel = UserModel(dictionary: tokendic)


        let parame = ["access_token":tokendic["access_token"] as! String,"uid" : tokendic["uid"] as! String]
        
        self.request(.GET, URLString: UserURLString, parameter: parame, Right: { (result) in
            
            if let dic =  result as? [String : AnyObject]{
                
                SVProgressHUD.dismiss()

                let userinfo: UserModel = user.setProperyWithDict(dic)
                userinfo.SaveUserMode()
                
                
                Complete(usermode : userinfo)
            }
            }, Wrong: { (Error) in
                
                WithError(errors: Error)
        })
    }
    
    func GetWeiboInformation(since_id:String,max_id:String,URLStr: String,Complete:(Infos:Array<[String : AnyObject]>?,Error: NSError?)->()){
        
        request(.GET, URLString:URLStr, parameter: ["access_token" : (ViewModel.sharViewModel.UserInfo?.access_token)! ,"since_id":since_id,"max_id":max_id], Right: { (result) in
                
            if let dic = result as? [String : AnyObject],
                infoarr = dic["statuses"] as? Array<[String : AnyObject]> {
                
                Complete(Infos: infoarr, Error: nil)
                
                return
            }
            Complete(Infos: nil, Error: NSError(domain: "获取微博信息失败", code: 11, userInfo: nil))
            
        }) { (Error) in
            
            Complete(Infos: nil, Error: Error)
        }
        
    }
    
    
    
    deinit{
        print("NetWorkTools Died")
    }
}
    

